package com.bls.executor;

import com.bls.executor.environment.MyMQ;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

public class MessageConsumer {

    public static void main(String[] args) throws Exception {
        for (int i = 0; i < 1; i++) {
            new Thread(()->{
                try {
                    Map<String, Channel> consumer = consumer(Thread.currentThread().getId());
                    Thread.sleep(3000);
                    StopMq.stop(consumer);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            },"consumer-"+i).start();
        }
    }

    private static Map<String, Channel> consumer(long threadId) throws Exception {
        Map<String, Channel> map = new Hashtable<>();
        MyMQ mq = new MyMQ();
        String EXCHANGE_NAME = "item_topic_exchange";//交换机名称，写死
        //todo 要监听的队列名称，可以用时间戳+随机数
        String queueName = "test";
        String routingKey = "314533857.设备故障";
        mq.channel.queueDeclare(queueName, false, false, false, null);
        mq.channel.queueBind(queueName, EXCHANGE_NAME, routingKey);//定义要监听的路由类型
        String tag = mq.channel.basicConsume(queueName, true, new Consumer() {
            @Override
            public void handleConsumeOk(String s) {

            }

            @Override
            public void handleCancelOk(String s) {
                System.out.println("已取消" + s);
            }

            @Override
            public void handleCancel(String s) throws IOException {

            }

            @Override
            public void handleShutdownSignal(String s, ShutdownSignalException e) {

            }

            @Override
            public void handleRecoverOk(String s) {

            }

            @Override
            public void handleDelivery(String s, Envelope envelope, AMQP.BasicProperties basicProperties, byte[] bytes) throws IOException {
                System.out.println(threadId+"收到消息为:" + new String(bytes) + ",路由为:" + routingKey);
            }
        });
        System.out.println(tag);
        map.put(tag, mq.channel);
        return map;
    }
}
